package com.example.diskfilesystem.disk;

import config.Config;

import java.io.IOException;
import java.util.Arrays;


//磁盘初始化类
public class DiskInitializer {

    public static void initialize(Disk disk) throws IOException {
        //初始化 FAT 表（128项，每项1字节）
        byte[] fat = new byte[Config.BLOCK_COUNT];
        //标记所有块为空闲块
        Arrays.fill(fat, Config.FREE);

        //系统块（0,1,2）保留
        fat[0] = Config.END;
        fat[1] = Config.END;
        fat[2] = Config.END;

        //坏块设为 254
        fat[23] = Config.BAD;
        fat[49] = Config.BAD;

        //写入FAT表到块0和块1（64字节 × 2块 = 128项）
        disk.writeBlock(0, Arrays.copyOfRange(fat, 0, Config.BLOCK_SIZE));
        disk.writeBlock(1, Arrays.copyOfRange(fat, Config.BLOCK_SIZE, Config.BLOCK_COUNT));

        //初始化根目录块（每块8个目录项，每项8字节）
        byte[] rootBlock = new byte[Config.BLOCK_SIZE];
        for (int i = 0; i < Config.BLOCK_SIZE; i += 8) {
            rootBlock[i] = '$';  // '$'表示空目录项
        }
        disk.writeBlock(Config.ROOT_BLOCK, rootBlock);

        //disk.close();
        //System.out.println("Disk initialization completed.");
    }

}
